<script setup>
import GoBackAndSearchNav from "@/components/GoBackAndSearchNav.vue";
import {onBeforeMount, ref, watchEffect} from 'vue'
import {delAddressAPI, getAddressAPI, saveAddressAPI, updateAddressAPI} from "@/api/address.js";
import { areaList } from '@vant/area-data';
import {useRouter, useRoute} from 'vue-router'
import {showConfirmDialog} from "vant";
import 'vant/es/dialog/style'

const router = useRouter()
const route = useRoute()

const address = ref({})
const area = ref('')
onBeforeMount(async () => {
  const id = Number.parseInt(route.query.id);
  (await getAddressAPI()).forEach(
      item => {
        if (item.id === id) address.value = item
      }
  )
})
watchEffect(() => {
  area.value = address.value.province + '/' + address.value.city + '/' + address.value.county
})

const floatPanelVisible = ref(false)
const anchors = ref([window.innerHeight * 0.5, window.innerHeight * 0.85])
const onOpenPanel = async () => {
  floatPanelVisible.value = true
}
const onClosePanel = () => {
  floatPanelVisible.value = false
}
const onConfirm = (selected) => {
  address.value.province = selected.selectedOptions[0].text
  address.value.city = selected.selectedOptions[1].text
  address.value.county = selected.selectedOptions[2].text
  onClosePanel()
}

const onSave = async () => {
  const res = await updateAddressAPI(address.value)
  if (res) {
    router.back()
  }
}
const onDelete = () => {
  showConfirmDialog({
    message: '是否确认删除收货地址'
  }).then(async () => {
    // on confirm
    const res = await delAddressAPI(address.value)
    if (res) {
      router.back()
    }
  }).catch(() => {
    // on cancel
  });
}
</script>

<template>
  <div class="address-list">
    <GoBackAndSearchNav :title="'修改收货地址'" :placeholder="true"></GoBackAndSearchNav>
    <van-field v-model="address.name" label="姓名" placeholder="请输入姓名" maxlength="20" clearable/>
    <van-field v-model="address.phone" label="手机号" placeholder="请输入手机号" maxlength="11" clearable/>
    <van-field
        @click-input="onOpenPanel"
        v-model="area"
        label="地区"
        right-icon="arrow"
        readonly
        placeholder="显示图标"
    />
    <van-field v-model="address.address" label="详细地址" placeholder="请输入详细地址" maxlength="200" clearable/>
    <van-cell title="是否默认">
      <template #value>
        <van-switch v-model="address.idDefault" size="20"/>
      </template>
    </van-cell>
    <div class="p-2 mt-2">
      <van-button type="primary" round block @click="onSave">保存</van-button>
    </div>
    <div class="p-2">
      <van-button type="default" round block @click="onDelete">删除</van-button>
    </div>
    <van-overlay :show="floatPanelVisible" @click="onClosePanel" lock-scroll></van-overlay>
    <van-floating-panel :anchors="anchors" v-show="floatPanelVisible">
      <van-area title="地区选择" :area-list="areaList" @confirm="onConfirm" @cancel="onClosePanel"/>
    </van-floating-panel>
  </div>
</template>

<style scoped lang="scss">

</style>